
import SendMessage from "../message/SendMessage";
import Service from "./Service";
export default class WXSocketService extends Service {
    
    protected socket;


    destroy(){
        if(this.socket != null){
            this.socket.close();
            this.socket = null;
        }
    }
    //手动重联
    reConnect(){
        this.connect(this.url,this.port);
    }

    onData(event){
        super.onData(event.data);
    }  
    connect(url:string,port?:number){
        super.connect(url,port);
        this.destroy();
        try{
            this.socket = wx.connectSocket({
                url: url,
                header: {
                    "content-type": "application/octet-stream",
                    "accept": "application/octet-stream",
                },
                method: "POST",
                protocols:[],
                success: function (res) {
                    cc.log("WS连接成功, ", res);
                },
                fail: function (res) {
                    cc.log("WS连接失败, ", res);
                },
                complete: function (res) {
                    cc.log("complete ", res);
                 },
            });
            this.socket.onOpen(this.onOpen.bind(this));
            this.socket.onMessage(this.onData.bind(this));
            this.socket.onError(this.onError.bind(this));
            this.socket.onClose(this.onClose.bind(this));           
        }catch(error){
            cc.log("WebService connect error "+error);
        } 
    }

    sendData(message:SendMessage){
        if(this.isReady()){
            let msg = message.getData();
            this.socket.send({
                data: msg,
                success: function (res) {
                },
                fail: function (res) {
                },
                complete: function (res) { },
            });
        } else {
            cc.warn(" 请先连接服务器 ",this.url);
        }            
    }
    

}
